/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import bean.Animal;
import bean.AnimalType;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

/**
 *
 * @author Eletro Shopping
 */
public class AnimalDAO extends GenericDAO {
    
    private static final long serialVersionUID = 1L;

    public AnimalDAO() {
    }
    
    public int addAnimal(Animal an) throws SQLException {
        an.setId(getNextId("ANIMALS"));
        String query = "INSERT INTO ANIMALS (ID,ID_OWNER,NAME,TYPE,BREED,AGE) VALUES (?,?,?,?,?,?)";
        executeCommand(query, an.getId(), an.getOwner().getId(), an.getName(), an.getType().toString(), an.getBreed(), an.getAge());
        return an.getId();
    }
    
    public void removeAnimal(int idAnimal) throws SQLException{
        executeCommand("DELETE FROM ANIMALS WHERE ID = ?", idAnimal);
    }
    
    public void updateAnimal(Animal an) throws SQLException {
        String query = "UPDATE ANIMALS SET ID_OWNER = ?,NAME=?,TYPE=?,BREED=?,AGE=? WHERE ID = ?";
        executeCommand(query, an.getOwner().getId(), an.getName(), an.getType().toString(), an.getBreed(), an.getAge(),an.getId());
    }
    
    public Animal getAnimal(int idAnimal) throws SQLException{
        ResultSet rs  = executeQuery("SELECT * FROM ANIMALS WHERE ID = ?", idAnimal);
        Animal an = null;
        while(rs.next()){
            an = populateAnimal(rs);
        }
        rs.close();
        return  an;
    }
    
     public List<Animal> getAnimalByName(String name) throws SQLException {
        List<Animal> toReturn = new LinkedList<Animal>();
        ResultSet rs = executeQuery("SELECT * FROM ANIMALS WHERE NAME LIKE ?", name + "%");
        while (rs.next()) {
            toReturn.add(populateAnimal(rs));
        }
        rs.close();
        return toReturn;
    }

    public static Animal populateAnimal(ResultSet rs) throws SQLException {
        final CustomerDAO customerDAO = new CustomerDAO();
        Animal toReturn = new Animal();
        toReturn.setId(rs.getInt("ID"));
        toReturn.setOwner(customerDAO.getCustomer(rs.getInt("ID_OWNER")));
        toReturn.setName(rs.getString("NAME"));
        toReturn.setType(AnimalType.valueOf(rs.getString("TYPE")));
        toReturn.setBreed(rs.getString("BREED"));
        toReturn.setAge(rs.getInt("AGE"));
        return toReturn;
    }
}
